package com.h3c.ptability.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.h3c.ptability.bo.PtEsignRecordBO;
import com.h3c.ptability.dto.electronicSign.PtEsignRecordDTO;
import com.h3c.ptability.entity.PtEsignRecord;
import com.h3c.ptability.entity.PtEsignRecordInfo;
import com.h3c.ptability.enums.ElectronicSignRecordStatus;
import com.h3c.ptability.mapstruct.PtEsignRecordInfoMapstruct;
import com.h3c.ptability.mapstruct.PtEsignRecordMapstruct;
import com.h3c.ptability.service.IPtEsignRecordInfoService;
import com.h3c.ptability.service.IPtEsignRecordService;
import com.h3c.ptability.support.ResultData;
import com.h3c.ptability.vo.PtEsignRecordInfoVO;
import com.h3c.ptability.vo.PtEsignRecordVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;


/**
 * 员工签署明细电子文件记录控制层
 *
 * @author chenyifan
 * @since 2022-05-19 10:19:59
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/ptEsignRecord")
public class PtEsignRecordController {
    /**
     * 服务对象
     */
    private final IPtEsignRecordService ptEsignRecordService;

    private final IPtEsignRecordInfoService recordInfoService;

    /**
     * feign调用根据预备员工id和场景类型获取最新的一条签署记录的文件信息
     *
     * @param workerId
     * @param sceneType
     * @return
     */
    @GetMapping(value = "/getRecentRecordInfo")
    public List<PtEsignRecordInfoVO> getRecentRecordInfo(@RequestParam String workerId,
                                                         @RequestParam Integer sceneType) {
        PtEsignRecord one = ptEsignRecordService.getOne(new QueryWrapper<PtEsignRecord>().lambda()
                .eq(PtEsignRecord::getWorkerId, workerId)
                .eq(PtEsignRecord::getSceneType, sceneType)
                .eq(PtEsignRecord::getSignStatus, ElectronicSignRecordStatus.SIGN_SUCCESS)
                .orderByDesc(PtEsignRecord::getSignBeginTime)
                .last("limit 1")
        );
        if (one != null) {
            String recordId = one.getRecordId();
            return PtEsignRecordInfoMapstruct.INSTANCE.entityListToVoList(recordInfoService.list(new QueryWrapper<PtEsignRecordInfo>().lambda()
                    .eq(PtEsignRecordInfo::getRecordId, recordId)
            ));
        } else {
            return new ArrayList<>();
        }

    }

    /**
     * 通过主键查询单条数据
     *
     * @param ptEsignRecord 参数对象
     * @return 单条数据
     */
    @GetMapping(value = "/get")
    public ResultData<PtEsignRecordBO> selectOne(PtEsignRecord ptEsignRecord) {
        PtEsignRecord result = ptEsignRecordService.getById(ptEsignRecord.getRecordId());
        PtEsignRecordBO esignRecordBO = PtEsignRecordMapstruct.INSTANCE.entityToBO(result);
        List<PtEsignRecordInfo> recordInfos = recordInfoService.getRecordInfosByRecordId(esignRecordBO.getRecordId());
        List<PtEsignRecordInfoVO> recordInfoVOS = PtEsignRecordInfoMapstruct.INSTANCE.entityListToVoList(recordInfos);
        recordInfoVOS.forEach(s->s.setStatusName(s.getStatus().getStatusName()));
        esignRecordBO.setInfoVOList(recordInfoVOS);
        if (result != null) {
            return ResultData.data(esignRecordBO, "查询成功");
        }
        return ResultData.fail("查询失败");
    }

    /**
     * 获取签署成功和非成功的数量
     *
     * @param recordDTO 参数对象
     * @return 成功共和非成功数量
     */
    @PostMapping(value = "/getSignSuccessPer")
    public ResultData<Map<String, Integer>> selectOne(@RequestBody PtEsignRecordDTO recordDTO) {
        LambdaQueryWrapper<PtEsignRecord> queryWrapper = new QueryWrapper<PtEsignRecord>().lambda();
        HashMap<String, Integer> result = new HashMap<>(5);
        if (Objects.nonNull(recordDTO.getSignStatus())) {
            queryWrapper.eq(PtEsignRecord::getSignStatus, recordDTO.getSignStatus());
        }
        if (StringUtils.hasText(recordDTO.getWorkerId())) {
            queryWrapper.eq(PtEsignRecord::getWorkerId, recordDTO.getWorkerId());
        }
        if (Objects.nonNull(recordDTO.getSceneType())) {
            queryWrapper.eq(PtEsignRecord::getSceneType, recordDTO.getSceneType());
        }
        if (StringUtils.hasText(recordDTO.getAppId())) {
            queryWrapper.eq(PtEsignRecord::getAppId, recordDTO.getAppId());
        }
        if (Objects.nonNull(recordDTO.getSignBeginTime())) {
            queryWrapper.ge(PtEsignRecord::getSignBeginTime, recordDTO.getSignBeginTime());
            queryWrapper.lt(PtEsignRecord::getSignBeginTime, DateUtil.offsetDay(recordDTO.getSignBeginTime(), 1));
        }
        int searchTotal = ptEsignRecordService.count(queryWrapper);
        if (searchTotal == 0) {
            result.put("searchTotal", 0);
            result.put("successCount", 0);
            return ResultData.data(result);
        }
        result.put("searchTotal", searchTotal);
        if (Objects.nonNull(recordDTO.getSignStatus())) {
            if (recordDTO.getSignStatus().equals(ElectronicSignRecordStatus.SIGN_SUCCESS) || recordDTO.getSignStatus().equals(ElectronicSignRecordStatus.WASTE_SIGN_FINISH)) {
                result.put("successCount", searchTotal);
                result.put("percent", 100);
            } else {
                result.put("successCount", 0);
                result.put("percent", 0);
            }
        } else {
            queryWrapper.in(PtEsignRecord::getSignStatus, Arrays.asList(ElectronicSignRecordStatus.SIGN_SUCCESS, ElectronicSignRecordStatus.WASTE_SIGN_FINISH));
            int successCount = ptEsignRecordService.count(queryWrapper);
            result.put("successCount", successCount);
            result.put("percent", BigDecimal.valueOf(successCount).divide(BigDecimal.valueOf(searchTotal), 3, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)).intValue());
        }
        return ResultData.data(result);
    }


    /**
     * 待条件的分页查询
     *
     * @param recordDTO
     * @return
     */
    @PostMapping(value = "/selectPage")
    public ResultData<IPage<PtEsignRecordVO>> selectPage(@RequestBody PtEsignRecordDTO recordDTO) {
        IPage<PtEsignRecordVO> result = ptEsignRecordService.selectPage(recordDTO);
        return ResultData.data(result);
    }

    /**
     * 导出签署记录
     *
     * @param recordDTO
     * @return
     */
    @PostMapping(value = "/downloadRecord")
    public ResultData<String> downloadRecord(@RequestBody PtEsignRecordDTO recordDTO,
                                   HttpServletResponse response) {
        try {
            ptEsignRecordService.downloadRecord(recordDTO,response);
            return null;
        } catch (Exception e) {
            log.error("下载失败:{}",e.getMessage());
            return ResultData.fail("下载失败:{}",e.getMessage());
        }
    }

}

